import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
import subPub from '../../../../utils/subPub';
import {
	getOptimizeDateTwo,
	initLocationPersmiss
} from '../../../../utils/util';
const app = getApp();
const $api = require('../../../../request/api').API;
const innerAudioContext = wx.createInnerAudioContext();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		expand: false,
		initNum: 2,
		steps: [],
		showOrderStep: false,
		//--------------------------------------------
		// 订单id
		orderId: '',
		// 订单编号
		orderNo: '',
		// 呼叫器id
		beeperId: '',
		//是不是主用户
		mainFlag: '',
		// 商家id
		businessId: '',
		// 住户id
		houseId: '',
		//----------------------订单基本信息----------------------------------------
		nums: '',
		payAmount: '',
		realAmount: '',
		promoterRealAmount: '',
		depositAmount: '',
		payableAmount: '',
		promoteGain: '',
		lastAmount: '',
		orderFlag: '',
		orderState: '',
		payState: '',
		createDate: '',
		completeDate: '',
		cancelDate: '无',
		cancelReason: '无',
		packageFee: '',
		infoState: '',
		orderRemark: '',
		voiceRemark: '',
		isPlayVoice: false,
		businessVoice: '',
		isPlayBusinessVoice: false,
		timingState: '',
		timingType: '',
		goodsType: '',
		serviceMode: '', //1表示服务上门
		// 商品列表
		goodsList: [],
		//--------------------商户信息-------------------------------------
		businessName: '',
		businessLinkName: '',
		businessLinkPhone: '',
		businessAddress: '',
		//--------------------服务员信息-------------------------------------
		waiterId: '',
		waiterName: '',
		waiterPhone: '',
		//------------ 用户信息（呼叫器名称、联系人、联系电话、详细地址）-------------------
		beeperName: '',
		linkName: '',
		phone: '',
		address: '',
		fullAddress: '',
		//------------ 评价信息（服务评分、商户评分、上门时间评分、总评分、评价详情）-------------------
		businessScore: '',
		waiterEvaluate: '',
		businessEvaluate: '',

		// 评价状态（0.未评价 1.已评价）
		evaluateState: 0,

		// 设置取消原因弹框
		showCancelOverlay: false,
		// 取消原因
		cancelReasonInput: '',

		// 设置评价弹框
		showEvaluationOverlay: false,

		//服务评分
		goodsScore: 0,
		MerchantsValue: 0,
		waiterScore: 0,
		totalValue: 0,

		// 评价详情
		evaluationInput: '',

		// 设置务员查看待支付订单是否展示二维码
		showQrcodeOverlay: false,
		// 二维码图片地址
		qrcodeImg: '',

		// 支付方式 1是余额支付，2是微信支付，3是货到付款
		payType: '',
		formListDetail: [],
		btnId: '',
		btnName: '',
		btnType: '',
		classifyIds: '',
		queryType: '',
		provinceName: '',
		cityName: '',
		areaName: '',
		latitude: '',
		longitude: '',
		houseNumber: '',
		ordersUserId: '',
		// 选择支付弹框
		showPayDialog: false,
		// 支付方式
		myPayType: 1,
		againShow: false,

		// 需要上传图片的订单状态12或者20
		errorState: '',
		// 打印状态
		printState: '',
		expectedTime: '',
		urls: [],
		promoterFlag: [],
		orderType: '',
		rentTime: '',
		rentUnit: '',
		renewPrice: '',
		renewTime: '',
		renewUnit: '',
		backFlag: '',
		rentBeginDate: '',
		rentEndDate: '',
		startFee: '',
		rentPrice: '',
		ruleId: '',
		appointmentState: '',
		invoice: '',
		showQueryResult: false, // 显示结果查询
		alarmType: '',
		currentAddress: '',
		discountOld: '',
		rebateOld: '',
		discountPmc: '',
		rebatePmc: '',
	},
	onLoad(options) {
		let id = options.orderId;
		let mainFlag = options.mainFlag;
		this.setData({
			orderId: id
		});
		if (mainFlag) {
			this.setData({
				mainFlag
			});
		}
	},
	onShow() {
		if (!this.data.againShow) {
			this.getData();
			this.setData({
				againShow: true
			});
		}
	},
	// 再来一单
	anotherOrder() {
		let shopCartData = [];
		$api.againOrderInfo({
			orderId: this.data.orderId
		}).then(res => {
			let data = res.data.data;
			data.goodsList.forEach(item => {
				shopCartData.push({
					ruleId: data.ruleId,
					businessId: data.businessId,
					businessName: data.businessName,
					id: item.beeperBtnId,
					nums: item.nums,
					salePrice: item.salePrice,
					packageFee: item.packageFee,
					mainImage: item.images,
					fastFlag: item.fastFlag,
					goodsId: item.goodsId,
					serverId: item.serverId,
					thirdClassifyId: item.thirdClassifyId,
					variantId: item.variantId,
					name: item.name,
					goodsType: item.goodsType,
					specVal: item.strSpecVal,
					relationVariantId: item.variantIds || [],
					relationNames: item.oGRelations && item.oGRelations.length ? item.oGRelations.map(item => item.name).toString() : ''
				});
			});
			wx.setStorageSync('shopCartData', JSON.stringify(shopCartData));
			initLocationPersmiss().then(res => {
				app.globalData['btnList.beeperId'] = this.data.beeperId;
				app.globalData['btnList.latitude'] = res.location.lat;
				app.globalData['btnList.longitude'] = res.location.lng;
				app.globalData['btnList.btnId'] = this.data.btnId;
				app.globalData['btnList.btnServerClassifyIds'] = this.data.classifyIds;
				app.globalData['btnList.queryType'] = this.data.queryType;
				wx.navigateTo({
					url: '/subcontract/home/pages/submitOrder/index?another=1'
				});
			});
		});
	},
	// 图片预览
	imagePreview(e) {
		let url = e.currentTarget.dataset.url;
		wx.previewImage({
			urls: this.data.urls,
			current: url
		});
	},
	// 继续支付
	async continuePay(e) {
		let beeperId = this.data.beeperId;
		let realAmount = this.data.realAmount;
		let lastAmount = this.data.lastAmount;
		let payState = this.data.payState;
		let orderNo = this.data.orderNo;
		let mainFlag = this.data.mainFlag;
		let goodsType = this.data.goodsType;
		if (beeperId) {
			let res = await this.getBeeperBalance(beeperId);
			if (mainFlag && goodsType != 3 && ((payState == 1 && realAmount < res) || (payState == 4 && lastAmount < res))) {
				this.setData({
					showPayDialog: true,
					orderNo: orderNo,
					myPayType: 1
				});
			} else {
				this.setData({
					myPayType: 2,
					orderNo: orderNo
				});
				this.confrimPay();
			}
		} else {
			this.setData({
				myPayType: 2,
				orderNo: orderNo
			});
			this.confrimPay();
		}
	},
	// 支付方式
	payChange(val) {
		let type = val.currentTarget.dataset.type;
		this.setData({
			myPayType: type
		});
	},
	// 确认支付
	confrimPay() {
		let myPayType = this.data.myPayType;
		let params = {
			orderNos: this.data.orderNo,
			openId: wx.getStorageSync(Storage.USER_OPEN_ID),
			payType: myPayType
		};
		if (myPayType == 1) {
			Toast.loading({
				message: '支付中',
				forbidClick: true,
				mask: true
			});
		}
		$api.scanToPayWaitOrder(params).then(res => {
			let data = res.data.data;
			if (myPayType == 1) {
				Toast.success({
					message: '支付成功',
					forbidClick: true,
					mask: true
				});
				setTimeout(() => {
					this.getData();
				}, 1000);
			} else if (myPayType == 2) {
				let _this = this;
				wx.requestPayment({
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.package,
					signType: data.signType,
					paySign: data.paySign,
					success: res => {
						Toast.success({
							message: '支付成功',
							forbidClick: true
						});
						setTimeout(() => {
							_this.getData();
						}, 1000);
					},
					fail: err => {
						Toast.fail({
							message: '支付失败',
							forbidClick: true
						});
					},
					complete: res => {}
				});
			}
		});
	},
	// 查询余额
	async getBeeperBalance(beeperId) {
		let params = {
			id: beeperId
		};
		let res = await $api.getBeeperBalance(params);
		return res.data.data;
	},
	// 展开获取收起
	clickExpand() {
		this.setData({
			expand: true
		});
	},
	// 点击收起
	clickStow() {
		this.setData({
			expand: false
		});
	},
	// 显示订单步骤弹框
	showOrderStepPopup() {
		$api.orderOperation({
			orderId: this.data.orderId
		}).then(res => {
			console.log(res.data.data);
			this.setData({
				steps: res.data.data
			});
			if (res.data.data.length > 0) {
				this.setData({
					showOrderStep: true
				});
			} else {
				Toast.fail('暂无记录');
			}
		});
	},
	// 隐藏订单弹框
	hideOrderStepPopup() {
		this.setData({
			showOrderStep: false
		});
	},
	showPromoterPrice(e) {
		console.log(e);
		this.setData({
			promoterFlag: e.detail
		});
	},
	// 详情数据
	async getData() {
		let params = {
			id: this.data.orderId
		};
		const res = await $api.orderDetail(params);
		let data = res.data.data;
		this.setData({
			orderId: data.orderId,
			beeperId: data.beeperId,
			businessId: data.businessId,
			houseId: data.houseId,
			waiterId: data.waiterId,
			orderNo: data.orderNo,
			payAmount: data.payAmount,
			orderSource: data.orderSource,
			nums: data.nums,
			realAmount: data.realAmount,
			promoterRealAmount: parseFloat((data.realAmount + data.promoteGain).toFixed(2)),
			lastAmount: data.lastAmount,
			orderFlag: data.orderTag,
			errorState: data.errorState,
			orderState: data.orderState,
			payState: data.payState,
			createDate: data.createDate,
			completeDate: data.completeDate,
			cancelDate: data.cancelDate,
			cancelReason: data.cancelReason,
			businessName: data.businessName,
			businessLinkName: data.businessLinkName,
			businessLinkPhone: data.businessLinkPhone,
			businessAddress: data.businessAddress,
			beeperName: data.beeperName,
			linkName: data.linkName,
			phone: data.phone,
			address: data.address,
			// goodsScore: data.goodsScore,
			waiterScore: data.waiterScore,
			businessScore: data.businessScore,
			waiterEvaluate: data.waiterEvaluate,
			businessEvaluate: data.businessEvaluate,
			// totalScore: data.totalScore,
			// evaluateDesc: data.evaluateDesc,
			evaluateState: data.evaluateState,
			waiterName: data.waiterName,
			waiterPhone: data.waiterPhone,
			packageFee: data.packageFee,
			// goodsList: data.goodsList,
			deliveryAmount: data.deliveryAmount,
			packageAmount: data.packageAmount,
			payableAmount: data.payableAmount,
			depositAmount: data.depositAmount,
			promoteGain: data.promoteGain,
			payType: data.payType,
			infoState: data.infoState,
			btnId: data.btnId,
			btnName: data.btnName,
			btnType: data.btnType,
			queryType: data.queryType,
			classifyIds: data.btnServerClassifyIds,
			latitude: data.lngLat.split(',')[1],
			longitude: data.lngLat.split(',')[0],
			// provinceName: data.provinceName,
			// cityName: data.cityName,
			// areaName: data.areaName,
			harvestAddressId: data.harvestAddressId,
			// houseNumber: data.houseNumber,
			ordersUserId: data.ordersUserId,
			voiceRemark: data.voiceRemark,
			businessVoice: data.businessVoice,
			orderRemark: data.orderRemark,
			orderType: data.orderType,
			timingState: data.timingState,
			timingType: data.timingType,
			rentTime: data.rentTime,
			rentUnit: data.rentUnit,
			renewPrice: data.renewPrice,
			renewTime: data.renewTime,
			renewUnit: data.renewUnit,
			printState: data.printState,
			expectedTime: data.expectedTime ? getOptimizeDateTwo(data.expectedTime) : '',
			serviceMode: data.serviceMode,
			backFlag: data.backFlag,
			rentBeginDate: data.rentBeginDate,
			rentEndDate: data.rentEndDate,
			startFee: data.startFee,
			rentPrice: data.rentPrice,
			urls: data.urls || [],
			ruleId: '',
			appointmentState: data.appointmentState,
			invoice: data.invoice,
			alarmType: data.alarmType,
			currentAddress: data.currentAddress,
			discountOld: data.discountOld,
			rebateOld: data.rebateOld,
			discountPmc: data.discountPmc,
			rebatePmc: data.rebatePmc,
		});
		let fullAddress = '';
		if (data.provinceName) fullAddress += data.provinceName;
		if (data.cityName) fullAddress += data.cityName;
		if (data.areaName) fullAddress += data.areaName;
		if (data.streetName) fullAddress += data.streetName;
		if (data.villageName) {
			fullAddress += data.villageName;
		} else {
			fullAddress = fullAddress + (data.address || '');
		}
		if (data.houseNumber) fullAddress += data.houseNumber;

		data.goodsList.forEach(item => {
			if (item.oGRelations) {
				item.oGRelations.forEach(item2 => {
					const flag = item2.sku == '无' || !item2.sku;
					item2.name = item2.name + (flag ? '' : '/' + item2.sku);
				});
			}
		});

		this.setData({
			fullAddress,
			goodsList: data.goodsList
		});
		this.getFormInfo();
	},
	// 查询结果
	async queryResult() {
		Toast.loading({
			message: '查询中,请稍等',
			duration: 0
		});
		let res = await $api.listKlabReportUrl({
			orderId: this.data.orderId
		});
		res = res.data.data || '';
		if (!res) {
			Toast.fail('暂未查询到结果');
			return;
		}
		wx.downloadFile({
			url: res,
			success: res2 => {
				Toast.clear();
				wx.openDocument({
					filePath: res2.tempFilePath,
					fileType: 'pdf',
					showMenu: true
				});
			},
			complete() {
				Toast.clear();
			}
		});
	},
	// 查看发票
	checkInvoice() {
		wx.previewImage({
			urls: [this.data.invoice],
			current: this.data.invoice
		});
	},
	playAudio(e) {
		let {
			type,
			index,
			index2,
			item
		} = e.currentTarget.dataset;
		if (type != '1' && type != '2' && type != '3') return;
		let {
			voiceRemark,
			businessVoice,
			formListDetail,
			isPlayVoice,
			isPlayBusinessVoice
		} = this.data;
		innerAudioContext.stop();
		formListDetail.forEach(item => item.list.forEach(item2 => (item2.isPlay = false)));
		this.setData({
			isPlayVoice: false,
			isPlayBusinessVoice: false,
			formListDetail
		});
		switch (type) {
			case '1':
				if (!isPlayVoice) {
					innerAudioContext.src = voiceRemark;
					innerAudioContext.play();
				}
				e;
				break;
			case '2':
				if (!isPlayBusinessVoice) {
					innerAudioContext.src = businessVoice;
					innerAudioContext.play();
				}
				break;
			case '3':
				if (!item.isPlay) {
					innerAudioContext.src = item.value;
					innerAudioContext.play();
				}
				break;
		}
		innerAudioContext.offPlay();
		innerAudioContext.offEnded();
		innerAudioContext.onPlay(() => {
			switch (type) {
				case '1':
					isPlayVoice = true;
					break;
				case '2':
					isPlayBusinessVoice = true;
					break;
				case '3':
					formListDetail[index].list[index2].isPlay = true;
					break;
			}
			this.setData({
				isPlayVoice,
				isPlayBusinessVoice,
				formListDetail
			});
		});
		// innerAudioContext.onStop(()=>{
		//   formListDetail.forEach(item=>item.list.forEach(item2=>item2.isPlay=false))
		//   this.setData({
		//     isPlayVoice:false,
		//     isPlayBusinessVoice:false,
		//     formListDetail,
		//   })
		// })
		innerAudioContext.onEnded(() => {
			formListDetail.forEach(item => item.list.forEach(item2 => (item2.isPlay = false)));
			this.setData({
				isPlayVoice: false,
				isPlayBusinessVoice: false,
				formListDetail
			});
		});
	},

	// 复制订单编号
	clipBoardOrderNo() {
		wx.setClipboardData({
			//准备复制的数据内容
			data: this.data.orderNo,
			success: res => {
				// Toast.success('复制成功');
				console.log(this.data.orderNo);
			}
		});
	},
	// 服务评分
	onServiceChange(event) {
		this.setData({
			goodsScore: event.detail
		});
	},
	// 商户评分
	onMerchantsChange(event) {
		this.setData({
			MerchantsValue: event.detail
		});
	},
	// 上门时间评分
	onTimeChange(event) {
		this.setData({
			waiterScore: event.detail
		});
	},
	// 总评分
	onTotalChange(event) {
		this.setData({
			totalValue: event.detail
		});
	},

	// 获取取消原因框输入的内容
	cancelReasonInput(e) {
		let value = e.detail.value;
		this.setData({
			cancelReasonInput: value
		});
	},
	// 获取评价详情框输入的内容
	evaluationInput(e) {
		let value = e.detail.value;
		this.setData({
			evaluationInput: value
		});
		console.log('评价详情输入的内容是 ' + value);
	},

	// 打开评价弹框
	openEvaluationOverlay() {
		wx.navigateTo({
			url: '/subcontract/order/pages/evaluate/index?orderId=' + this.data.orderId
		});
		// this.setData({
		//   showEvaluationOverlay: true
		// })
	},
	// 关闭评价弹框
	closeEvaluationOverlay() {
		this.setData({
			showEvaluationOverlay: false
		});
	},
	// 确认评价
	evaluationOrder() {
		let params = {
			orderId: this.data.orderId,
			goodsScore: this.data.goodsScore,
			businessScore: this.data.MerchantsValue,
			waiterScore: this.data.waiterScore,
			totalScore: this.data.totalValue,
			evaluateDesc: this.data.evaluationInput
		};
		$api
			.evaluationOrder(params)
			.then(res => {
				console.log('评价订单', res);
				if (res.data.status == 0) {
					Toast.success('评价订单成功');
					setTimeout(() => {
						this.setData({
							showEvaluationOverlay: false
						});
						this.getData();
					}, 1000);
				}
			})
			.catch(err => {
				console.log('评价订单', err);
			});
	},
	// 用户确认
	confirmModify(e) {
		let params = {
			id: this.data.orderId,
			state: 1
		};
		Toast.loading({
			duration: 0, // 持续展示 toast
			forbidClick: true,
			message: '正在处理',
			mask: true
		});
		$api
			.confirmModify(params)
			.then(res => {
				Toast.clear();
				Toast.success('操作成功');
				this.setData({
					infoState: 0
				});
				this.getData();
			})
			.catch(() => {
				Toast.clear();
			});
	},
	// 打开取消订单弹框
	openCanceOverlay() {
		this.setData({
			showCancelOverlay: true
		});
	},
	// 关闭取消订单弹框
	closeCanceOverlay() {
		this.setData({
			showCancelOverlay: false
		});
	},
	// 确认取消订单
	async cancelOrder() {
		const {
			cancelReasonInput,
			orderId
		} = this.data;
		let params = {
			cancelReason: cancelReasonInput,
			orderId
		};
		Toast.loading({
			duration: 0, // 持续展示 toast
			forbidClick: true,
			message: '正在处理',
			mask: true
		});
		const res = await $api.cancelOrder(params);
		Toast.clear();
		if (res.data.status == 0) {
			Toast.success('操作成功');
			this.setData({
				showCancelOverlay: false
			});
			await this.getData();

			// 取消订单后获取上一页的订单列表，需要把订单列表的当前订单的订单状态改变为已取消
			// const page = getCurrentPages().at(-2)
			// const dataList = page.data.dataList
			// const target = dataList.find(item => item.orderId == this.data.orderId)
			// if (target) {
			//   target.orderState = this.data.orderState
			//   target.payState = this.data.payState
			// }
			// page.setData({
			//   dataList,
			// })

			const {
				orderState,
				payState,
				errorState
			} = this.data;
			subPub.emit('orderModifyState', {
				orderId,
				orderState,
				payState,
				errorState
			});
		}
	},
	// 打开待支付支付二维码
	openQrcodeOverlay() {
		$api.getPayWxUrlById({
			beeperId: this.data.beeperId
		}).then(res => {
			this.setData({
				showQrcodeOverlay: true,
				qrcodeImg: res.data.data
			});
		});
	},
	// 关闭查看二维码
	closeQrcodeOverlay() {
		this.setData({
			showQrcodeOverlay: false
		});
	},

	/**
	 * 图片预览
	 * @param {*} e
	 */
	imgPreview(e) {
		const list = [];
		list.push(String(e.currentTarget.dataset.src));
		wx.previewImage({
			current: e.currentTarget.dataset.src,
			urls: list
		});
	},
	// 拨打电话
	callPhone(e) {
		let phone = e.currentTarget.dataset.phone;
		wx.makePhoneCall({
			phoneNumber: phone, //仅为示例，并非真实的电话号码
			success: function () {
				console.log('拨打电话成功！');
			},
			fail: function () {
				console.log('拨打电话失败！');
			}
		});
	},
	// 获取表单信息
	getFormInfo() {
		$api.getFormInfoByOrder({
			orderId: this.data.orderId
		}).then(res => {
			let arr = res.data.data || [];
			let formList = [];
			let obj = null;
			let showQueryResult = false;
			for (let key in arr) {
				//这里是为了排序把附加信息放在最后面
				if (key == '0') {
					!showQueryResult && (showQueryResult = arr[key].some(item => item.fieldName == 'barcode'));
					obj = {
						name: '附加信息',
						list: arr[key],
						introduce: arr[key][0].introduce || ''
					};
				} else {
					formList.push({
						name: arr[key][0].goodsName || arr[key][0].serverName || '附加信息',
						list: arr[key],
						introduce: arr[key][0].introduce || ''
					});
					!showQueryResult && (showQueryResult = arr[key].some(item => item.fieldName == 'barcode'));
				}
			}
			if (obj) {
				formList.push(obj);
			}
			let formListDetail = JSON.parse(JSON.stringify(formList));
			formListDetail.forEach(item => {
				this.formatFormList(item.list);
			});
			this.setData({
				formList,
				formListDetail,
				showQueryResult
			});
		});
	},
	// 格式化表单数据
	formatFormList(val) {
		val.forEach(item => {
			let fieldType = item.fieldType;
			let value = item.value;
			let fieldOptions = item.fieldOptions ? JSON.parse(item.fieldOptions) : [];
			switch (fieldType) {
				case 2:
					if (value) {
						let temp = value.split(',');
						// let arr =
						let str = '';
						if (fieldOptions.length) {
							temp.forEach(item => {
								let name = fieldOptions.find(item2 => item2.id == item).name;
								if (str) {
									str = str + ',' + name;
								} else {
									str = name;
								}
							});
						} else {
							str = temp;
						}

						item.value = str;
					} else {
						item.value = '';
					}
					break;
				case 3:
					if (value && value.split(',').length > 1) {
						item.value = value.split(',')[0] + ' - ' + value.split(',')[1];
					} else {
						item.value = value || '';
					}
					break;
				case 4:
					if (value) {
						item.value = value.split(',');
					} else {
						item.value = '';
					}
					break;
				case 6:
					if (value && fieldOptions.length && typeof fieldOptions[0] == 'object') {
						item.value = fieldOptions.find(item => item.id == value).name;
					}
					break;
				case 7:
					if (value) {
						item.value = JSON.parse(value).address;
					}
					break;
				default:
					item.value = value || '';
			}
		});
	},
	// 计时开始结束
	timing(e) {
		const state = e.currentTarget.dataset.state;
		Dialog.confirm({
			title: '提示',
			message: state == 1 ? '确认开始?' : '确定结束?'
		}).then(() => {
			const params = {
				state,
				id: this.data.orderId
			};
			$api.timingOrderOperate(params).then(res => {
				this.getData();
			});
		});
	},
	// 预览表单图片
	previewFormImg(e) {
		let val = e.currentTarget.dataset;
		wx.previewImage({
			current: val.url,
			urls: [...val.list]
		});
	},

	/**
	 * 救援进度点击 前往救援详情界面
	 */
	handleRescueProgressClick() {
		wx.navigateTo({
			url: `/subcontract/order/pages/rescueProgress/index?orderId=${this.data.orderId}`
		});
	},
	/**
	 * 转诊记录
	 */
	handleReferralRecordClick() {
		const {
			orderId
		} = this.data;
		wx.navigateTo({
			url: `/subcontract/order/pages/referralRecord/index?orderId=${orderId}`
		});
	}
});